Option Explicit On
Option Strict On

'Copyright (c) 2007-2010, William Severance, Jr., WESNet Designs
'All rights reserved.

'Redistribution and use in source and binary forms, with or without modification, are permitted
'provided that the following conditions are met:

'Redistributions of source code must retain the above copyright notice, this list of conditions
'and the following disclaimer.

'Redistributions in binary form must reproduce the above copyright notice, this list of conditions
'and the following disclaimer in the documentation and/or other materials provided with the distribution.

'Neither the name of William Severance, Jr. or WESNet Designs may be used to endorse or promote
'products derived from this software without specific prior written permission.

'Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
'            OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
'            AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE
'            FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
'            LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
'            INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
'            OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
'            IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'Although I will try to answer questions regarding the installation and use of this software when
'such questions are submitted via e-mail to the below address, no promise of further
'support or enhancement is made nor should be assumed.

'Developer Contact Information:
'     William Severance, Jr.
'     WESNet Designs
'     679 Upper Ridge Road
'     Bridgton, ME 04009
'     Phone: 207-647-9375
'     E-Mail: bill@wesnetdesigns.com
'     Website: www.wesnetdesigns.com
'
Imports DotNetNuke
Imports DotNetNuke.Services.Exceptions
Imports System.Text
Imports System.IO
Imports System.Xml


Namespace WESNet.DNN.Modules.EPrayer
    Partial Class EMailTemplateEditor
        Inherits DotNetNuke.Framework.UserControlBase

#Region "Private Members"
        Private _LocalResourceFile As String
        Private Const SessionKeyPrefix As String = "EMail_Template_File"
        Private Const BaseTemplateFileName As String = "EMail.xml"
        Private _PortalTemplatePath As String

#End Region

#Region "Public Properties"

        Public Property LocalResourceFile() As String
            Get
                Dim fileRoot As String

                If _LocalResourceFile = "" Then
                    fileRoot = ModulePath & Localization.LocalResourceDirectory & "/EMailTemplateEditor"
                Else
                    fileRoot = _LocalResourceFile
                End If
                Return fileRoot
            End Get
            Set(ByVal Value As String)
                _LocalResourceFile = Value
            End Set
        End Property

        Public ReadOnly Property ModulePath() As String
            Get
                Return Me.TemplateSourceDirectory & "/"
            End Get
        End Property

        Public ReadOnly Property HostTemplatePath() As String
            Get
                Return ModulePath & "Templates/"
            End Get
        End Property

        Public ReadOnly Property PortalTemplatePath() As String
            Get
                If _PortalTemplatePath Is Nothing Then
                    Dim _path As String = PortalSettings.HomeDirectory & Regex.Replace(ModulePath, Common.ApplicationPath & "/DesktopModules/", "", RegexOptions.IgnoreCase) & "Templates/"
                    Dim _mappedPath As String = HttpContext.Current.Server.MapPath(_path)
                    If Not Directory.Exists(_mappedPath) Then
                        Try
                            Directory.CreateDirectory(_mappedPath)
                            Dim _mappedHostTemplatePath As String = HttpContext.Current.Server.MapPath(HostTemplatePath)
                            For Each f As FileInfo In New DirectoryInfo(_mappedHostTemplatePath).GetFiles()
                                f.CopyTo(_mappedPath & f.Name)
                            Next
                        Catch exc As Exception
                            Throw New ModuleLoadException("EMailTemplateEditor - Cannot create portal template path '" & _PortalTemplatePath & "'.", exc)
                        End Try
                    End If
                    _PortalTemplatePath = _path
                End If
                Return _PortalTemplatePath
            End Get
        End Property

        Public Property TemplateScope() As String
            Get
                Return rblTemplateScope.SelectedValue
            End Get
            Set(ByVal value As String)
                value = value.Trim()
                If value.Length >= 1 Then
                    value = value.Substring(0, 1).ToUpper
                    If value = "H" OrElse value = "P" Then
                        rblTemplateScope.SelectedValue = value
                        Exit Property
                    End If
                End If
                Throw New ArgumentOutOfRangeException("TemplateScope", "Must be 'H' or 'P'")
            End Set
        End Property

        Public Property TemplatePath() As String
            Get
                If ViewState("TemplatePath") Is Nothing Then
                    If TemplateScope = "H" Then
                        Return HostTemplatePath
                    Else
                        Return PortalTemplatePath
                    End If
                Else
                    Return CType(ViewState("TemplatePath"), String)
                End If
            End Get
            Set(ByVal value As String)
                ViewState("TemplatePath") = value
            End Set
        End Property

        Public Property MailFormat() As Services.Mail.MailFormat
            Get
                If ViewState("MailFormat") Is Nothing Then
                    Return Services.Mail.MailFormat.Text
                Else
                    Return CType(ViewState("MailFormat"), Services.Mail.MailFormat)
                End If
            End Get
            Set(ByVal value As Services.Mail.MailFormat)
                ViewState("MailFormat") = value
            End Set
        End Property

        Public Property DefaultStyleName() As String
            Get
                If ViewState("DefaultStyleName") Is Nothing Then
                    If MailFormat = Services.Mail.MailFormat.Html Then
                        Return "Default"
                    Else
                        Return "TEXT"
                    End If
                Else
                    Return CType(ViewState("DefaultStyleName"), String)
                End If
            End Get
            Set(ByVal value As String)
                ViewState("DefaultStyleName") = value
            End Set
        End Property

        Public ReadOnly Property CurrentDocument() As XmlDocument
            Get
                Dim SessionKey As String = SessionKeyPrefix & "_" & TemplateFileName
                Dim obj As Object = Session(SessionKey)
                If obj Is Nothing Then
                    obj = OpenXmlDocument()
                    Session(SessionKey) = obj
                End If
                Return CType(obj, XmlDocument)
            End Get
        End Property

        Private Property TemplateFileName() As String
            Get
                If ddlTemplateFileName.SelectedValue = "-1" Then
                    If trAddTemplateFile.Visible Then
                        Return tbNewTemplateFileName.Text
                    Else
                        Return BaseTemplateFileName
                    End If
                Else
                    Return ddlTemplateFileName.SelectedValue
                End If
            End Get
            Set(ByVal value As String)
                Dim li As ListItem = ddlTemplateFileName.Items.FindByText(value)
                If Not li Is Nothing Then
                    ddlTemplateFileName.SelectedIndex = ddlTemplateFileName.Items.IndexOf(li)
                End If
            End Set
        End Property

        Private Property CurrentTemplateName() As String
            Get
                If ViewState("CurrentTemplateName") Is Nothing Then
                    Return String.Empty
                Else
                    Return CType(ViewState("CurrentTemplateName"), String)
                End If
            End Get
            Set(ByVal value As String)
                ViewState("CurrentTemplateName") = value
            End Set
        End Property

        Private Property CurrentStyleName() As String
            Get
                If ViewState("CurrentStyleName") Is Nothing Then
                    Return String.Empty
                Else
                    Return CType(ViewState("CurrentStyleName"), String)
                End If
            End Get
            Set(ByVal value As String)
                ViewState("CurrentStyleName") = value
            End Set
        End Property

        Private Property TemplateName() As String
            Get
                If ddlTemplateName.SelectedValue = "-1" Then
                    If trAddTemplate.Visible Then
                        Return tbNewTemplateName.Text
                    Else
                        Return String.Empty
                    End If
                Else
                    Return ddlTemplateName.SelectedValue
                End If
            End Get
            Set(ByVal value As String)
                Dim li As ListItem = ddlTemplateName.Items.FindByText(value)
                If Not li Is Nothing Then
                    ddlTemplateName.SelectedIndex = ddlTemplateName.Items.IndexOf(li)
                End If
            End Set
        End Property

        Private Property StyleName() As String
            Get
                If ddlStyleName.SelectedValue = "-1" Then
                    If trAddStyle.Visible Then
                        Return tbNewStyleName.Text
                    Else
                        Return DefaultStyleName
                    End If
                Else
                    Return ddlStyleName.SelectedValue
                End If
            End Get
            Set(ByVal value As String)
                Dim li As ListItem = ddlStyleName.Items.FindByText(value)
                If Not li Is Nothing Then
                    ddlStyleName.SelectedIndex = ddlStyleName.Items.IndexOf(li)
                End If
            End Set
        End Property

#End Region

#Region "Private Methods"

        Private Function OpenXmlDocument() As XmlDocument
            Dim xmlDoc As XmlDocument
            Dim filepath As String = HttpContext.Current.Server.MapPath(TemplatePath & TemplateFileName)
            If File.Exists(filepath) Then
                Try
                    xmlDoc = New XmlDocument
                    xmlDoc.Load(filepath)
                    Return xmlDoc
                Catch exc As Exception
                    Throw New XmlException("Unable to load EMail template file '" & filepath & "' - " & exc.Message)
                End Try
            Else
                Throw New System.IO.IOException("EMail template file '" & filepath & "' does not exist.")
            End If
        End Function

        Private Sub SaveXmlDocument()
            Dim filepath As String = HttpContext.Current.Server.MapPath(TemplatePath & TemplateFileName)
            If File.Exists(filepath) Then
                Dim backuppath As String = filepath & ".backup"
                If File.Exists(backuppath) Then File.Delete(backuppath)
                File.Copy(filepath, backuppath)
            End If
            Try
                CurrentDocument.Save(filepath)
            Catch exc As Exception
                Throw New System.IO.IOException("EMail template file cannot be saved to the path: '" & filepath & "' - " & exc.Message)
            End Try
        End Sub

        Private Sub ResetCurrentDocument()
            Dim SessionKey As String = SessionKeyPrefix & "_" & TemplateFileName
            Session.Remove(SessionKey)
        End Sub

        Private Sub LoadEMailTemplate(ByVal TemplateName As String, ByVal StyleName As String)

            If TemplateName <> "" AndAlso StyleName <> "" Then

                Dim TemplateNode As XmlNode
                Dim BodyNode As XmlNode

                Try
                    TemplateNode = CurrentDocument.SelectSingleNode("//Template[@Name='" & TemplateName & "']")
                Catch exc As Exception
                    ShowErrorMessage("Template named '" & TemplateName & "' could not be loaded from template file '" & TemplatePath & TemplateFileName & "' - " & exc.Message)
                    Exit Sub
                End Try

                Try
                    tbSubject.Text = TemplateNode.SelectSingleNode("Subject").InnerText
                    BodyNode = TemplateNode.SelectSingleNode("Styles/Body[@Style='" & StyleName & "']")
                    Dim Body As String = BodyNode.InnerText
                    If StyleName = "TEXT" Then
                        Body = Utilities.ReplacevbCrlf(Body)
                        teBody.Mode = "BASIC"
                        teBody.TextRenderMode = "Text"
                    Else
                        teBody.Mode = "RICH"
                        teBody.TextRenderMode = "Html"
                    End If
                    teBody.Text = Body
                Catch exc As Exception
                    ShowErrorMessage("Subject and/or Body for style named '" & StyleName & "' could not be loaded from template named '" & _
                                         TemplateName & "' in template file '" & TemplatePath & TemplateFileName & "' - " & exc.Message)
                End Try
            End If
        End Sub

        Private Sub UpdateEMailTemplate(ByVal TemplateName As String, ByVal StyleName As String)
            If TemplateName <> "" AndAlso StyleName <> "" Then
                Dim TemplateNode As XmlNode
                Dim BodyNode As XmlNode

                Try
                    TemplateNode = CurrentDocument.SelectSingleNode("//Template[@Name='" & TemplateName & "']")
                Catch exc As Exception
                    ShowErrorMessage("Template named '" & TemplateName & "' could not be accessed in template file '" & TemplatePath & TemplateFileName & "' - " & exc.Message)
                    Exit Sub
                End Try

                Try
                    Dim SubjectNode As XmlNode = TemplateNode.SelectSingleNode("Subject")
                    SubjectNode.InnerText = Utilities.StripHTMLTags(tbSubject.Text)

                    BodyNode = TemplateNode.SelectSingleNode("Styles/Body[@Style='" & StyleName & "']")
                    Dim Body As String = Server.HtmlDecode(teBody.Text)
                    If StyleName = "TEXT" Then
                        Body = Utilities.StripHTMLTags(Body)
                    End If
                    If BodyNode.HasChildNodes AndAlso BodyNode.FirstChild.Name = "#cdata-section" Then
                        BodyNode.FirstChild.InnerText = Body
                    Else
                        Body = "<![CDATA[" & Body & "]]>"
                        BodyNode.InnerXml = Body
                    End If

                Catch exc As Exception
                    ShowErrorMessage("Subject and/or Body for style named '" & StyleName & "' in template named '" & _
                                         TemplateName & "' in template file '" & TemplatePath & TemplateFileName & "' could not be updated - " & exc.Message)
                End Try
            End If
        End Sub

        Private Sub ShowMessage(ByVal Text As String)
            ShowMessage(Text, "Normal")
        End Sub

        Private Sub ShowMessage(ByVal Text As String, ByVal CssClass As String)
            With lblMessage
                .Text = Text
                .CssClass = CssClass
                .Visible = True
            End With
        End Sub

        Private Sub ShowErrorMessage(ByVal Text As String)
            ShowMessage(Text, "NormalRed")
        End Sub

        Private Sub ClearMessage()
            With lblMessage
                .Text = ""
                .Visible = False
            End With
        End Sub

        Private Sub LoadTemplateFiles(ByVal SelectedFileName As String)
            Dim TemplateFileNames As String() = Utilities.GetTemplateFileNames(TemplatePath & SelectedFileName)
            With ddlTemplateFileName
                .DataSource = TemplateFileNames
                .DataBind()
                .Items.Add(New ListItem(Localization.GetString("Add_New_Template_File", LocalResourceFile), "-1"))
                If SelectedFileName = "" Then
                    TemplateFileName = BaseTemplateFileName
                Else
                    TemplateFileName = SelectedFileName
                End If
            End With
            ResetCurrentDocument()
            LoadTemplates("")
        End Sub

        Private Sub LoadTemplates(ByVal SelectedTemplateName As String)
            If Not CurrentDocument Is Nothing Then
                Dim TemplateNames As String() = Utilities.GetTemplateNames(CurrentDocument.CreateNavigator())
                With ddlTemplateName
                    .DataSource = TemplateNames
                    .DataBind()
                    .Items.Add(New ListItem(Localization.GetString("Add_New_Template", LocalResourceFile), "-1"))
                    If SelectedTemplateName = "" Then
                        .SelectedIndex = 0
                    Else
                        TemplateName = SelectedTemplateName
                    End If

                End With
                CurrentTemplateName = TemplateName
                LoadStyles(DefaultStyleName)
            End If
        End Sub

        Private Sub LoadStyles(ByVal SelectedStyleName As String)
            If TemplateName <> "" Then
                Dim StyleNames As String() = Utilities.GetStyleNames(CurrentDocument.CreateNavigator(), TemplateName)
                With ddlStyleName
                    .DataSource = StyleNames
                    .DataBind()
                    .Items.Add(New ListItem(Localization.GetString("Add_New_Style", LocalResourceFile), "-1"))
                    If SelectedStyleName = "" Then
                        .SelectedIndex = 0
                    Else
                        StyleName = SelectedStyleName
                    End If
                End With
                CurrentStyleName = StyleName
                LoadEMailTemplate(TemplateName, StyleName)
            End If
        End Sub

        Private Function AddTemplate(ByVal XmlDoc As XmlDocument, ByVal NewTemplateName As String, ByVal CopyCurrentTemplate As Boolean) As XmlNode
            Dim TemplatesNode As XmlNode = XmlDoc.SelectSingleNode("Templates")
            Dim NewTemplateNode As XmlNode

            If CopyCurrentTemplate Then
                Try
                    Dim SourceTemplateNode As XmlNode = CurrentDocument.SelectSingleNode("//Template[@Name='" & CurrentTemplateName & "']")
                    NewTemplateNode = TemplatesNode.AppendChild(XmlDoc.ImportNode(SourceTemplateNode, True))
                    NewTemplateNode.Attributes("Name").Value = NewTemplateName
                    Return NewTemplateNode
                Catch exc As Exception
                    Throw New XmlException("Unable to create clone of current template '" & CurrentTemplateName & "' - " & exc.Message)
                End Try
            Else
                NewTemplateNode = TemplatesNode.AppendChild(XmlDoc.CreateElement("Template"))
                NewTemplateNode.Attributes.Append(XmlDoc.CreateAttribute("Name")).Value = NewTemplateName
                NewTemplateNode.AppendChild(XmlDoc.CreateElement("Subject")).InnerText = Localization.GetString("Enter_Subject_Here", LocalResourceFile)
                Dim StylesNode As XmlNode = NewTemplateNode.AppendChild(XmlDoc.CreateElement("Styles"))
                AddStyle(XmlDoc, NewTemplateName, "Default", False)
                AddStyle(XmlDoc, NewTemplateName, "TEXT", False)
                Return NewTemplateNode
            End If
        End Function

        Private Function AddStyle(ByVal XmlDoc As XmlDocument, ByVal TemplateName As String, ByVal NewStyleName As String, ByVal CopyCurrentStyle As Boolean) As XmlNode
            Dim StylesNode As XmlNode = XmlDoc.SelectSingleNode("//Template[@Name='" & TemplateName & "']/Styles")
            Dim NewStyleNode As XmlNode
            If CopyCurrentStyle Then
                Try
                    Dim SourceStyleNode As XmlNode = CurrentDocument.SelectSingleNode("//Template[@Name='" & TemplateName & "']/Styles/Body[@Style='" & CurrentStyleName & "']")
                    NewStyleNode = StylesNode.AppendChild(XmlDoc.ImportNode(SourceStyleNode, True))
                    NewStyleNode.Attributes("Style").Value = NewStyleName
                    Return NewStyleNode
                Catch exc As Exception
                    Throw New XmlException("Unable to create clone of current style '" & CurrentStyleName & "' from template '" & TemplateName & "' - " & exc.Message)
                End Try
            Else
                NewStyleNode = StylesNode.AppendChild(XmlDoc.CreateElement("Body"))
                NewStyleNode.Attributes.Append(XmlDoc.CreateAttribute("Style")).Value = StyleName
                If NewStyleName.ToLower = "text" Then
                    NewStyleNode.AppendChild(XmlDoc.CreateCDataSection(Localization.GetString("Enter_TEXTBody_Here", LocalResourceFile)))
                Else
                    NewStyleNode.AppendChild(XmlDoc.CreateCDataSection(Localization.GetString("Enter_HTMLBody_Here", LocalResourceFile)))
                End If
                Return NewStyleNode
            End If
        End Function
#End Region

#Region "Event Handlers"

        Protected Sub rblTemplateScope_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rblTemplateScope.SelectedIndexChanged
            LoadTemplateFiles(BaseTemplateFileName)
        End Sub

        Protected Sub ddlTemplateFilename_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlTemplateFileName.SelectedIndexChanged
            If ddlTemplateFileName.SelectedValue = "-1" Then
                trAddTemplateFile.Visible = True
            Else
                UpdateEMailTemplate(CurrentTemplateName, StyleName)
                trAddTemplate.Visible = False
                ResetCurrentDocument()
                LoadTemplates("")
            End If
        End Sub

        Protected Sub ddlTemplateName_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlTemplateName.SelectedIndexChanged
            If ddlTemplateName.SelectedValue = "-1" Then
                trAddTemplate.Visible = True
            Else
                If TemplateName <> CurrentTemplateName Then
                    UpdateEMailTemplate(CurrentTemplateName, StyleName)
                    CurrentTemplateName = TemplateName
                End If
                trAddTemplate.Visible = False
                LoadStyles(DefaultStyleName)
            End If
        End Sub

        Protected Sub ddlStyleName_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlStyleName.SelectedIndexChanged
            If ddlStyleName.SelectedValue = "-1" Then
                trAddStyle.Visible = True
            Else
                If StyleName <> CurrentStyleName Then
                    UpdateEMailTemplate(TemplateName, CurrentStyleName)
                    CurrentStyleName = StyleName
                End If
                trAddStyle.Visible = False
                LoadEMailTemplate(TemplateName, StyleName)
            End If
        End Sub

        Protected Sub cmdAddTemplateFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdAddTemplateFile.Click
            If tbNewTemplateFileName.Text.Length = 0 Then
                ShowErrorMessage(Localization.GetString("No_Filename_Specified"))
                DotNetNuke.Common.SetFormFocus(tbNewTemplateFileName)
                Exit Sub
            End If
            Dim NewTemplateFileName As String = tbNewTemplateFileName.Text
            If Path.GetExtension(NewTemplateFileName) <> ".xml" Then
                NewTemplateFileName = NewTemplateFileName & ".xml"
            End If
            If Array.IndexOf(Utilities.GetTemplateFileNames(TemplatePath), NewTemplateFileName) >= 0 Then
                ShowErrorMessage(String.Format(Localization.GetString("File_Already_Exists"), NewTemplateFileName))
                DotNetNuke.Common.SetFormFocus(tbNewTemplateFileName)
                Exit Sub
            End If
            If cbCopyTemplateFile.Checked Then
                Dim NewFilePath As String = HttpContext.Current.Server.MapPath(TemplatePath & NewTemplateFileName)
                If File.Exists(NewFilePath) Then
                    Dim BackupFilePath As String = NewFilePath & ".backup"
                    If File.Exists(BackupFilePath) Then File.Delete(BackupFilePath)
                    File.Copy(NewFilePath, BackupFilePath)
                    File.SetAttributes(NewFilePath, FileAttributes.Normal)
                    File.Delete(NewFilePath)
                End If
                Try
                    Dim FilePath As String = HttpContext.Current.Server.MapPath(TemplatePath & TemplateFileName)
                    File.Copy(FilePath, NewFilePath)
                Catch exc As Exception
                    Throw New System.IO.IOException("New EMail template file cannot be saved to the path: '" & NewFilePath & "' - " & exc.Message)
                End Try
            Else
                'Create new xmldocument in memory
                Dim NewXmlDoc As New XmlDocument()
                Dim TemplatesNode As XmlNode
                NewXmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "no")
                TemplatesNode = NewXmlDoc.AppendChild(NewXmlDoc.CreateElement("Templates"))
                For Each TemplateName As String In Utilities.GetTemplateNames(CurrentDocument.CreateNavigator())
                    AddTemplate(NewXmlDoc, TemplateName, False)
                Next
                SaveXmlDocument()
            End If
            LoadTemplateFiles(NewTemplateFileName)
            trAddTemplateFile.Visible = False
        End Sub

        Protected Sub cmdAddTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdAddTemplate.Click
            If tbNewTemplateName.Text.Length = 0 Then
                ShowErrorMessage(Localization.GetString("No_TemplateName_Specified"))
                DotNetNuke.Common.SetFormFocus(tbNewTemplateName)
                Exit Sub
            End If
            Dim NewTemplateName As String = tbNewTemplateName.Text
            If Array.IndexOf(Utilities.GetTemplateNames(CurrentDocument.CreateNavigator), NewTemplateName) >= 0 Then
                ShowErrorMessage(String.Format(Localization.GetString("Template_Already_Exists"), NewTemplateName))
                DotNetNuke.Common.SetFormFocus(tbNewTemplateName)
                Exit Sub
            End If
            'Add the new template
            AddTemplate(CurrentDocument, NewTemplateName, cbCopyTemplate.Checked)
            LoadTemplates(NewTemplateName)
            trAddTemplate.Visible = False
        End Sub

        Protected Sub cmdAddStyle_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdAddStyle.Click
            If tbNewStyleName.Text.Length = 0 Then
                ShowErrorMessage(Localization.GetString("No_StyleName_Specified"))
                DotNetNuke.Common.SetFormFocus(tbNewStyleName)
                Exit Sub
            End If
            Dim NewStyleName As String = tbNewStyleName.Text
            If Array.IndexOf(Utilities.GetStyleNames(CurrentDocument.CreateNavigator, TemplateName), NewStyleName) >= 0 Then
                ShowErrorMessage(String.Format(Localization.GetString("Style_Already_Exists"), NewStyleName, TemplateName))
                DotNetNuke.Common.SetFormFocus(tbNewStyleName)
                Exit Sub
            End If
            'Add the new style
            For Each TemplateName As String In Utilities.GetTemplateNames(CurrentDocument.CreateNavigator)
                AddStyle(CurrentDocument, TemplateName, NewStyleName, cbCopyStyle.Checked)
            Next
            LoadStyles(NewStyleName)
            trAddStyle.Visible = False
        End Sub

        Protected Sub cmdUpdateTemplateFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpdateTemplateFile.Click
            UpdateEMailTemplate(TemplateName, StyleName)
            SaveXmlDocument()
        End Sub

        Protected Sub cmdUndoTemplateChanges_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUndoTemplateChanges.Click
            ResetCurrentDocument()
            LoadEMailTemplate(TemplateName, StyleName)
        End Sub

        Protected Sub EMailTemplateEditor_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            If DotNetNuke.Framework.AJAX.IsInstalled Then
                DotNetNuke.Framework.AJAX.RegisterPostBackControl(cmdUpdateTemplateFile)
            End If
        End Sub

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not IsPostBack Then
                If Entities.Users.UserController.GetCurrentUserInfo.IsSuperUser Then
                    rblTemplateScope.Enabled = True
                    TemplateScope = "H"
                Else
                    rblTemplateScope.Enabled = False
                    TemplateScope = "P"
                End If
                LoadTemplateFiles(BaseTemplateFileName)
            End If
        End Sub
#End Region

    End Class
End Namespace
